package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.place;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.CheckErrorException;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinet;
import com.gzhryc.shared_device.bxscn.code.dao.models.PortableEnergyBatteryPlaceCount;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyCabinetSearch;
import com.gzhryc.shared_device.cdb.code.dao.db.BatteryCabinet;
import com.gzhryc.shared_device.cdb.code.services.BatteryCabinetService;
import com.gzhryc.shared_device.cdb.code.services.dto.BatteryCabinetSearch;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.code.services.dto.ChargeSocketSearch;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.models.PlaceDeviceCount;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.config.FuncModelUrl;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceBusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceClerk;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStoreAddress;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.dao.models.PlaceUserCount;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceClerkService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreAddressService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreTypeService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.PlaceUserProfitDayStatistics;
import com.gzhryc.shared_device.oem.code.statistics.services.PlaceUserProfitDayStatisticsService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.ELoginUserRoleType;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.PowerCheckUtils;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceBusinessConfigDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceCostChangeRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceDeviceDeployRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceDeviceListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceDeviceListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceDeviceUndeployRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreAddressSaveRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreSaveRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlacePhysicalStoreSaveResponse;
import com.gzhryc.shared_device.pcl.code.dao.db.ChargingCable;
import com.gzhryc.shared_device.pcl.code.services.ChargingCableService;
import com.gzhryc.shared_device.pcl.code.services.dto.ChargingCableSearch;

public class PlaceController {
	
	static Logger log = Logger.getLogger(PlaceController.class);

    @Route(value = "/agent/api/v1/place/physical_store/list.data")
    public PlacePhysicalStoreListResponse list(HttpServletRequest request) {
        PlacePhysicalStoreListResponse apiResp = new PlacePhysicalStoreListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
        PlacePhysicalStoreListRequest apiReq = WebUtils.getJsonRequest(request, PlacePhysicalStoreListRequest.class);
        if(apiReq != null) {
            List<PlaceProfitUser> placeProfitUserList = null;
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                List<PlacePhysicalStore> data = null;
                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
                    search.setName(apiReq.getBody().getTrim());
                    search.setUserId(loginUser.getId());
                    data = PlacePhysicalStoreService.self().findJoinBySearch(search,apiReq.getBody().getPageNo(),WebConstants.PAGE_LIMIT);
                }else if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                	List<PlaceClerk> placeClerkList = PlaceClerkService.self().findByUserKeys(loginUser.getId(), loginUser.getParentId());
                	if(placeClerkList != null) {
                		List<Long> placeIds = new ArrayList<>();
                        for (PlaceClerk placeClerk : placeClerkList) {
                            placeIds.add(placeClerk.getPlaceId());
                        }

                        PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
                        search.setName(apiReq.getBody().getTrim());
                        search.setPlaceIds(placeIds);
                        data = PlacePhysicalStoreService.self().findJoinBySearch(search, apiReq.getBody().getPageNo(), WebConstants.PAGE_LIMIT);
                	}
                }else {
                    placeProfitUserList = PlaceProfitUserService.self().findByUserKeys(loginUser.getParentId(),loginUser.getId());
                    if(placeProfitUserList != null && placeProfitUserList.size() > 0) {
                        List<Long> placeIds = new ArrayList<>();
                        for (PlaceProfitUser placeProfitUser : placeProfitUserList) {
                            placeIds.add(placeProfitUser.getPlaceId());
                        }

                        PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
                        search.setName(apiReq.getBody().getTrim());
                        search.setPlaceIds(placeIds);
                        data = PlacePhysicalStoreService.self().findJoinBySearch(search, apiReq.getBody().getPageNo(), WebConstants.PAGE_LIMIT);
                    }
                }

                if (data != null && data.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    List<Long> placeIds = new ArrayList<>();
                    for (PlacePhysicalStore place : data) {
                        placeIds.add(place.getId());
                    }

                    List<PlaceUserCount> placeUserCountList = PlaceProfitUserService.self().findUserCountByPlaceId(placeIds);

                    String dayDate = DateFormatUtils.format(new Date(),"yyyyMMdd");
                    List<PlaceDeviceCount> placeDeviceCountList = DeviceService.self().findCountByPlaceIds(placeIds);
                    List<PlaceUserProfitDayStatistics> placeUserProfitDayStatisticsList = PlaceUserProfitDayStatisticsService.self()
                            .findByDayUserIdAndPlaceIds(loginUser.getId(),dayDate,placeIds);

                    List<PortableEnergyBatteryPlaceCount> batteryPlaceCountList = null;
                    if(BaseConstants.getBXSCN()) {
                        batteryPlaceCountList = PortableEnergyBatteryService.self().findPlaceCountByPlaceIds(placeIds);
                    }

                    String resDomain = WebConstants.getResDomain(request);
                    for (PlacePhysicalStore place : data) {
                        PlacePhysicalStoreListResponse.Item item = new PlacePhysicalStoreListResponse.Item();
                        item.setId(place.getId());
                        item.setName(place.getName());
                        item.setTypeNames(place.getTypeNames());
                        item.setProvince(place.getProvince());
                        item.setCity(place.getCity());
                        item.setCityArea(place.getCityArea());
                        if (StringTools.isNotBlank(place.getThumbnailImg())) {
                            item.setImgUrl(resDomain + place.getThumbnailImg());
                        }
                        if(placeProfitUserList != null && placeProfitUserList.size() > 0) {
                            for(PlaceProfitUser placeProfitUser : placeProfitUserList) {
                                if(placeProfitUser.getPlaceId().equals(place.getId())) {
                                    item.setRoleType(placeProfitUser.getRoleType());
                                    item.setRoleTypeName(placeProfitUser.getRoleTypeName());
                                    break;
                                }
                            }
                        }
                        item.setCreateDate(place.getCreateDate());

                        item.setUserCount(1L);
                        if(placeUserCountList != null && placeUserCountList.size() > 0){
                            for(PlaceUserCount placeUserCount : placeUserCountList){
                                if(placeUserCount.getPlaceId().equals(item.getId())){
                                    item.setUserCount(item.getUserCount() + placeUserCount.getUserCount());
                                    break;
                                }
                            }
                        }

                        item.setDeviceCount(0L);
                        item.setOnlineDeviceCount(0L);

                        if(placeDeviceCountList != null && placeDeviceCountList.size() > 0){
                            for(PlaceDeviceCount placeDeviceCount : placeDeviceCountList){
                                if(placeDeviceCount.getPlaceId().equals(item.getId())){
                                    item.setDeviceCount(placeDeviceCount.getDeviceCount());
                                    break;
                                }
                            }
                        }

                        if(batteryPlaceCountList != null && batteryPlaceCountList.size() > 0){
                            for(PortableEnergyBatteryPlaceCount batteryPlaceCount : batteryPlaceCountList){
                                if(batteryPlaceCount.getPlaceId().equals(item.getId())){
                                    item.setDeviceCount(item.getDeviceCount() + batteryPlaceCount.getDeviceCount());
                                    break;
                                }
                            }
                        }

                        item.setIncomeCount(0);
                        item.setIncomeMoneyStr("0");

                        if(placeUserProfitDayStatisticsList != null && placeUserProfitDayStatisticsList.size() > 0){
                            for(PlaceUserProfitDayStatistics placeUserProfitDayStatistics : placeUserProfitDayStatisticsList){
                                if(placeUserProfitDayStatistics.getPlaceId().equals(item.getId())){
                                    item.setIncomeCount(placeUserProfitDayStatistics.getIncomeCount());
                                    item.setIncomeMoneyStr(placeUserProfitDayStatistics.getIncomeMoneyStr());
                                    break;
                                }
                            }
                        }

                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/physical_store/info.data")
    public PlacePhysicalStoreInfoResponse info(HttpServletRequest request) {
        PlacePhysicalStoreInfoResponse apiResp = new PlacePhysicalStoreInfoResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
        PlacePhysicalStoreInfoRequest apiReq = WebUtils.getJsonRequest(request, PlacePhysicalStoreInfoRequest.class);
        if(apiReq != null && apiReq.getBody().getPlaceId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore == null) {
                    apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到网点");
                    return apiResp;
                }

                PlaceProfitUser profitUser = null;

                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (!physicalStore.getUserId().equals(loginUser.getId())) {
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                        return apiResp;
                    }
                }else {
                    profitUser = PlaceProfitUserService.self().getJoinByKeys(physicalStore.getId(),loginUser.getId());
                    if(profitUser == null){
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                        return apiResp;
                    }
                    if(!loginUser.getParentId().equals(profitUser.getPlaceUserId())){
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                        return apiResp;
                    }
                }

                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                apiResp.getBody().setId(physicalStore.getId());
                apiResp.getBody().setName(physicalStore.getName());
                apiResp.getBody().setTypeCodes(physicalStore.getTypeCodes());
                apiResp.getBody().setTypeNames(physicalStore.getTypeNames());
                apiResp.getBody().setProvince(physicalStore.getProvince());
                apiResp.getBody().setCity(physicalStore.getCity());
                apiResp.getBody().setCityArea(physicalStore.getCityArea());
                apiResp.getBody().setAddress(physicalStore.getAddress());
                apiResp.getBody().setRouteInfo(physicalStore.getRouteInfo());
                apiResp.getBody().setContactPhone(physicalStore.getContactPhone());
                apiResp.getBody().setLongitude(physicalStore.getLongitude());
                apiResp.getBody().setLatitude(physicalStore.getLatitude());
                if(physicalStore.getOpenTime() != null) {
                    apiResp.getBody().setOpenTime(DateTools.changeHHmm(physicalStore.getOpenTime()));
                }
                if(physicalStore.getCloseTime() != null) {
                    apiResp.getBody().setCloseTime(DateTools.changeHHmm(physicalStore.getCloseTime()));
                }
                apiResp.getBody().setThumbnailImg(physicalStore.getThumbnailImg());
                if (StringTools.isNotBlank(physicalStore.getThumbnailImg())) {
                    String resDomain = WebConstants.getResDomain(request);
                    apiResp.getBody().setImgUrl(WebUtils.setHttpDomain(resDomain,physicalStore.getThumbnailImg()));
                }
                apiResp.getBody().setCreateDate(physicalStore.getCreateDate());

                apiResp.getBody().setDeviceCount(0L);
                apiResp.getBody().setOnlineDeviceCount(0L);

                Long deviceCount = DeviceService.self().countByPlaceId(physicalStore.getId());
                Long batteryCount = null;
                if(BaseConstants.getBXSCN()) {
                    batteryCount = PortableEnergyBatteryService.self().countByPlaceId(physicalStore.getId());
                }
                if(deviceCount != null){
                    if(batteryCount != null){
                        apiResp.getBody().setDeviceCount(deviceCount + batteryCount);
                    }else{
                        apiResp.getBody().setDeviceCount(deviceCount);
                    }
                }else if(batteryCount != null){
                    apiResp.getBody().setDeviceCount(batteryCount);
                }
   
                if(profitUser != null) {
                    //用户信息
                    PlacePhysicalStoreInfoResponse.UserItem userItem = new PlacePhysicalStoreInfoResponse.UserItem();
                    userItem.setUserId(profitUser.getUserId());
                    userItem.setUserName(profitUser.getUser().getName());
                    userItem.setUserPhone(profitUser.getUser().getPhone());
                    userItem.setRoleType(profitUser.getRoleType());
                    userItem.setRoleTypeName(profitUser.getRoleTypeName());
                    userItem.setCreateDate(profitUser.getCreateDate());

                    if (StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
                        userItem.setIncomeRatioItems(new ArrayList<>());
                        IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                        for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                            PlacePhysicalStoreInfoResponse.IncomeRatioItem incomeRatioItem = new PlacePhysicalStoreInfoResponse.IncomeRatioItem();
                            incomeRatioItem.setBusinessType(item.getBusinessType());
                            incomeRatioItem.setBusinessTypeName(EBusinessType.note(item.getBusinessType()));
                            incomeRatioItem.setIncomeRatio(item.getIncomeRatio());
                            userItem.getIncomeRatioItems().add(incomeRatioItem);
                        }
                    }
                    apiResp.getBody().setUserItem(userItem);
                }
                
                if(ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType())) {
                	apiResp.getBody().setCanDeploy(true);
                	apiResp.getBody().setCanUndeploy(true);
                	apiResp.getBody().setEditFreeMember(true);
                	apiResp.getBody().setEditClerk(true);
                }else if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())) {
                	apiResp.getBody().setCanDeploy(true);
                	//获取权限
                	AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getParentId(), loginUser.getId());
                	if(agentRelation != null) {
                		if(agentRelation.getCanUndeployDevice() == 1) {
                			apiResp.getBody().setCanUndeploy(true);
                		}
                	}
             
                	if(profitUser != null && ERoleType.Partner.index().equals(profitUser.getRoleType())) {
	        			AgentRelationFuncModel funcModel = AgentRelationFuncModelService.self().getJoinByKeys(loginUser.getParentId(),loginUser.getId()
	        					,FuncModelUrl.MemberFreeList);
	        			if(funcModel != null && AgentRelationFuncModelEnum.State.Open.index().equals(funcModel.getState())) {
	        				apiResp.getBody().setEditFreeMember(true);
	        			}
	        		}
            	}else {
	                if(profitUser != null && ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
	        			AgentRelationFuncModel funcModel = AgentRelationFuncModelService.self().getJoinByKeys(loginUser.getParentId(),loginUser.getId()
	        					,FuncModelUrl.MerchantClerkMng);
	        			if(funcModel != null && AgentRelationFuncModelEnum.State.Open.index().equals(funcModel.getState())) {
	        				apiResp.getBody().setEditClerk(true);
	        			}
	        		}
            	}
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/physical_store/save.do")
    public PlacePhysicalStoreSaveResponse save(HttpServletRequest request) {
        PlacePhysicalStoreSaveResponse apiResp = new PlacePhysicalStoreSaveResponse(ClientAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        PlacePhysicalStoreSaveRequest apiReq = WebUtils.getJsonRequest(request, PlacePhysicalStoreSaveRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if(loginUser != null) {
            	if(ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType()) || ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())){
	                try {
	                	AgentRelation agentRelation = null;

	                	if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())){
	                		agentRelation = AgentRelationService.self().getByKeys(loginUser.getParentId(), loginUser.getId());
	                		if(agentRelation == null || !ERoleType.Partner.index().equals(agentRelation.getRoleType())) {
	                			apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到关联用户信息");
	 	                        return apiResp;
	                		}
	                	}
	                	
	                    PlacePhysicalStoreSaveRequest.Body body = apiReq.getBody();
	                    ValidateTools.check(body);
	
	                    if(!PowerCheckUtils.checkPlaceEditPower(loginUser,body.getId())){
	                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
	                        return apiResp;
	                    }
	
	                    PlacePhysicalStore physicalStore = new PlacePhysicalStore();
	                    physicalStore.setId(body.getId());
	
	                    if(StringTools.isBlank(body.getProvince()) || StringTools.isBlank(body.getCity()) || StringTools.isBlank(body.getCityArea())){
	                        apiResp.setMsg("请选择网点所在地区");
	                        return apiResp;
	                    }
	
	                    if(StringTools.isBlank(body.getThumbnailImg())){
	                        apiResp.setMsg("请上传网点的图片");
	                        return apiResp;
	                    }
	
	                    String code = CountryAreaUtils.getAreaIds(new String[]{body.getProvince(), body.getCity(), body.getCityArea()});
	                    if (StringUtils.isNotBlank(code)) {
	                        physicalStore.setAreaCode(code);
	                    } else {
	                        apiResp.setMsg("请选择网点所在地区");
	                        return apiResp;
	                    }
	
	                    String[] typeCodes = body.getTypeCodes().split(",");
	                    String[] typeName = PlacePhysicalStoreTypeService.self().getNames(typeCodes);
	                    if (typeName != null && typeName.length > 0) {
	                        physicalStore.setTypeCodes(body.getTypeCodes());
	                        physicalStore.setTypeNames(StringUtils.join(typeName,","));
	                    }else{
	                        apiResp.setMsg("网点类型不正确，请重新选择");
	                        return apiResp;
	                    }
	
	                    physicalStore.setName(body.getName());
	                    physicalStore.setThumbnailImg(body.getThumbnailImg());
	
	                    physicalStore.setProvince(body.getProvince());
	                    physicalStore.setCity(body.getCity());
	                    physicalStore.setCityArea(body.getCityArea());
	
	                    physicalStore.setLongitude(body.getLongitude());
	                    physicalStore.setLatitude(body.getLatitude());
	                    physicalStore.setAddress(body.getAddress());
	                    physicalStore.setRouteInfo(body.getRouteInfo());
	                    physicalStore.setContactPhone(body.getContactPhone());
	                    physicalStore.setOpenTime(DateTools.changeHHmm(body.getOpenTime()));
	                    physicalStore.setCloseTime(DateTools.changeHHmm(body.getCloseTime()));
	
	                    if(physicalStore.getId() != null){
	                        try {
	                            if (PlacePhysicalStoreService.self().updateNotNull(physicalStore)) {
	                                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                                apiResp.getBody().setPlaceId(physicalStore.getId());
	                            }
	                        } catch (LogicException e) {
	                            apiResp.setMsg(e.getMessage());
	                        }
	                    }else {
	                    	OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
	                        operateInfo.setOperator(loginUser.getRoleType(), loginUser.getFullName());
	                        operateInfo.setOperatorId(loginUser.getId());
	                 
	                        if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())){
	                            physicalStore.setUserId(loginUser.getParentId());
	                            try {
	                                if (PlacePhysicalStoreService.self().add(physicalStore,agentRelation,operateInfo)) {
	                                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                                    apiResp.getBody().setPlaceId(physicalStore.getId());
	                                }
	                            } catch (LogicException e) {
	                                apiResp.setMsg(e.getMessage());
	                            }
	                        }else if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
	                        	physicalStore.setUserId(loginUser.getId());
	                        	try {
	                                if (PlacePhysicalStoreService.self().add(physicalStore,operateInfo)) {
	                                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                                    apiResp.getBody().setPlaceId(physicalStore.getId());
	                                }
	                            } catch (LogicException e) {
	                                apiResp.setMsg(e.getMessage());
	                            }
	                        }
	                    }
	                } catch (CheckErrorException e) {
	                    apiResp.setMsg(e.getMessage());
	                } catch (LogicException e) {
	                    apiResp.setMsg(e.getMessage());
	                }
            	}else {
            		 apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                     return apiResp;
            	}
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/physical_store/address/save.do")
    public DefaultAPIResponse doAddress(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存失败，请稍后再试");
        PlacePhysicalStoreAddressSaveRequest apiReq = WebUtils.getJsonRequest(request, PlacePhysicalStoreAddressSaveRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getReceiveName())
                && StringTools.isNotBlank(apiReq.getBody().getReceivePhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if(loginUser != null) {
            	if(ERoleType.Agent.index().equals(loginUser.getRoleType()) || ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())) {
	                try {
	                    PlacePhysicalStoreAddressSaveRequest.Body body = apiReq.getBody();
	                    ValidateTools.check(body);
	
	                    if (StringTools.isBlank(body.getProvince()) || StringTools.isBlank(body.getCity()) || StringTools.isBlank(body.getCityArea())) {
	                        apiResp.setMsg("请选择网点所在地区");
	                        return apiResp;
	                    }
	
	                    PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
	                    if (physicalStore == null) {
	                        apiResp.setMsg("未找到网点信息");
	                        return apiResp;
	                    }
	
	                    if(!physicalStore.getUserId().equals(loginUser.getId())){
	                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
	                        return apiResp;
	                    }
	
	                    PlacePhysicalStoreAddress address = new PlacePhysicalStoreAddress();
	                    address.setPlaceId(apiReq.getBody().getPlaceId());
	                    address.setReceiveName(apiReq.getBody().getReceiveName());
	                    address.setReceivePhone(apiReq.getBody().getReceivePhone());
	                    address.setProvince(body.getProvince());
	                    address.setCity(body.getCity());
	                    address.setCityArea(body.getCityArea());
	                    address.setAddress(apiReq.getBody().getMailAddress());
	
	                    String code = CountryAreaUtils.getAreaIds(new String[]{body.getProvince(), body.getCity(), body.getCityArea()});
	                    if (StringUtils.isNotBlank(code)) {
	                        address.setAreaCode(code);
	                    } else {
	                        apiResp.setMsg("请选择网点所在地区");
	                        return apiResp;
	                    }
	
	                    if (PlacePhysicalStoreAddressService.self().save(address)) {
	                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                    }
	                } catch (CheckErrorException e) {
	                    apiResp.setMsg(e.getMessage());
	                }
            	}else {
            		apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
            	}
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/business_config/cost/change.do")
    public DefaultAPIResponse costChange(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "切换失败，请稍后再试");
        PlaceCostChangeRequest apiReq = WebUtils.getJsonRequest(request, PlaceCostChangeRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getBusinessType())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
            	Long userId = loginUser.getId();
            	if(!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            		if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())) {
            			userId = loginUser.getParentId();
            		}else {
            			apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            			return apiResp;
            		}
            	}
            	
            	
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if(physicalStore == null){
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }
                if(!physicalStore.getUserId().equals(userId)){
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
                }
                try {
                    if (PlaceBusinessConfigService.self().setFeeTemplateId(apiReq.getBody().getPlaceId(),
                    		apiReq.getBody().getBusinessType(), apiReq.getBody().getFeeTemplateId())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/business_config/del.do")
    public DefaultAPIResponse delBusinessConfig(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "切换失败，请稍后再试");
        PlaceBusinessConfigDelRequest apiReq = WebUtils.getJsonRequest(request, PlaceBusinessConfigDelRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getBusinessType())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if(physicalStore == null){
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }
                if(!physicalStore.getUserId().equals(loginUser.getId())){
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
                }
                try {
                    if (PlaceBusinessConfigService.self().deleteByKeys(apiReq.getBody().getPlaceId(), apiReq.getBody().getBusinessType())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

    /**
     * 获取网点部署的设备信息，无权限检查
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/place/device/list.data")
    public PlaceDeviceListResponse deviceList(HttpServletRequest request) {
        PlaceDeviceListResponse apiResp = new PlaceDeviceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        PlaceDeviceListRequest apiReq = WebUtils.getJsonRequest(request, PlaceDeviceListRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null) {
        	if(apiReq.getBody().getBusinessType() == null || apiReq.getBody().getBusinessType().equals("0")) {
        		List<PlaceBusinessConfig> businessConfigList = PlaceBusinessConfigService.self().findByPlaceId(apiReq.getBody().getPlaceId());
	            List<Device> deviceList = DeviceService.self().findByPlaceId(apiReq.getBody().getPlaceId());
	            if(deviceList != null && deviceList.size() > 0){
	                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
	                apiResp.getBody().setItems(new ArrayList<>());
	                
	                List<String> deviceSnList = new ArrayList<>();
	                for(Device device : deviceList){
	                	deviceSnList.add(device.getDeviceSn());
	                }
	                
	                List<PortableEnergyCabinet> bxscnDeviceList = null;
	                List<BatteryCabinet> cdbDeviceList = null;
	                List<ChargeSocket> cdczDeviceList = null;
	                List<ChargingCable> pclDeviceList = null;
	                boolean hasBXSCNShop = false;
	                
	                if(businessConfigList != null && businessConfigList.size() > 0) {
                    	for(PlaceBusinessConfig busiConfig : businessConfigList) {
                    		if(EBusinessType.BXSCN.index().equals(busiConfig.getBusinessType())){
                    			bxscnDeviceList = PortableEnergyCabinetService.self().findByDeviceSnList(deviceSnList);
                    		}else if(EBusinessType.CDB.index().equals(busiConfig.getBusinessType())){
                    			cdbDeviceList = BatteryCabinetService.self().findByDeviceSnList(deviceSnList);
                    		}else if(EBusinessType.CDCZ.index().equals(busiConfig.getBusinessType())){
                    			cdczDeviceList = ChargeSocketService.self().findByDeviceSnList(deviceSnList);
                    		}else if(EBusinessType.PCL.index().equals(busiConfig.getBusinessType())){
                    			pclDeviceList = ChargingCableService.self().findByDeviceSnList(deviceSnList);
                    		}else if(EBusinessType.BXSCN_SHOP.index().equals(busiConfig.getBusinessType())) {
                    			hasBXSCNShop = true;
                    		}
                    			
                    	}
                    }
	                
	                for(Device device : deviceList){
	                    PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
	                    item.setDeviceSn(device.getDeviceSn());
	                    item.setDeviceTypeId(device.getDeviceTypeId());
	                    item.setDeviceTypeName(device.getDeviceTypeName());
	                    item.setBindNote(device.getBindNote());
	                    item.setDeployDate(device.getDeployDate());
	                    if(StringTools.isNotBlank(device.getDeviceFunCodes()) && StringTools.isNotBlank(device.getDeviceFunNames())){
	                        item.setDeviceFunCodes(Arrays.asList(device.getDeviceFunCodes().split(",")));
	                        item.setDeviceFunNames(Arrays.asList(device.getDeviceFunNames().split(",")));
	                    }
	                    
	                    item.setState(0);
	                    item.setStateName("未知状态");
	                    
	                    if(bxscnDeviceList != null && bxscnDeviceList.size() > 0) {
	                    	for(PortableEnergyCabinet ccc : bxscnDeviceList) {
	                    		if(ccc.getDeviceSn().equals(item.getDeviceSn())) {
	                    			item.setState(ccc.getState());
	        	                    item.setStateName(ccc.getStateName());
	        	                    break;
	                    		}
	                    	}
	                    }
	                    if(item.getState() == 0 && cdbDeviceList != null && cdbDeviceList.size() > 0) {
	                    	for(BatteryCabinet ccc : cdbDeviceList) {
	                    		if(ccc.getDeviceSn().equals(item.getDeviceSn())) {
	                    			item.setState(ccc.getState());
	        	                    item.setStateName(ccc.getStateName());
	        	                    break;
	                    		}
	                    	}
	                    }
	                    if(item.getState() == 0 && cdczDeviceList != null && cdczDeviceList.size() > 0) {
	                    	for(ChargeSocket ccc : cdczDeviceList) {
	                    		if(ccc.getDeviceSn().equals(item.getDeviceSn())) {
	                    			item.setState(ccc.getState());
	        	                    item.setStateName(ccc.getStateName());
	        	                    break;
	                    		}
	                    	}
	                    }
	                    if(item.getState() == 0 && pclDeviceList != null && pclDeviceList.size() > 0) {
	                    	for(ChargingCable ccc : pclDeviceList) {
	                    		if(ccc.getDeviceSn().equals(item.getDeviceSn())) {
	                    			item.setState(ccc.getState());
	        	                    item.setStateName(ccc.getStateName());
	        	                    break;
	                    		}
	                    	}
	                    }
	                    apiResp.getBody().getItems().add(item);
	                }
	                
	                if(hasBXSCNShop) {
		            	//查询直接部署的储能电池
		                List<PortableEnergyBattery> batteryList = PortableEnergyBatteryService.self().findByPlaceId(apiReq.getBody().getPlaceId());
		                if (batteryList != null && batteryList.size() > 0) {
		                    if (apiResp.getBody().getItems() == null) {
		                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
		                        apiResp.getBody().setItems(new ArrayList<>());
		                    }
		                    for (PortableEnergyBattery device : batteryList) {
		                        PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
		                        item.setDeviceSn(device.getDeviceSn());
		                        item.setDeviceTypeId(device.getType());
		                        item.setDeviceTypeName(device.getTypeName());
		                        item.setState(device.getState());
		                        item.setStateName(device.getStateName());
		                        item.setBindNote(device.getBindNote());
		                        item.setDeployDate(device.getDeployDate());
		                        item.setDeviceFunCodes(new ArrayList<>());
		                        item.getDeviceFunCodes().add(EDeviceFunCode.BXSCN.index());
		                        item.setDeviceFunNames(new ArrayList<>());
		                        item.getDeviceFunNames().add(EDeviceFunCode.BXSCN.note());
		                        apiResp.getBody().getItems().add(item);
		                    }
		                }
		            }
	            }
        	}else {
        		if(EBusinessType.BXSCN.index().equals(apiReq.getBody().getBusinessType())) {
        			PortableEnergyCabinetSearch search = new PortableEnergyCabinetSearch();
        			search.setPlaceId(apiReq.getBody().getPlaceId());
        			List<PortableEnergyCabinet> deviceList = PortableEnergyCabinetService.self().findJoinBySearch(search);
        			if(deviceList != null && deviceList.size() > 0) {
        				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
    	                apiResp.getBody().setItems(new ArrayList<>());
    	                for(PortableEnergyCabinet device : deviceList){
    	                    PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
    	                    item.setDeviceSn(device.getDeviceSn());
    	                    item.setDeviceTypeId(device.getDeviceTypeId());
    	                    item.setDeviceTypeName(device.getDeviceTypeName());
    	                    item.setState(device.getState());
    	                    item.setStateName(device.getStateName());
    	                    item.setBindNote(device.getDevice().getBindNote());
    	                    item.setDeployDate(device.getDevice().getDeployDate());
    	                    if(StringTools.isNotBlank(device.getDevice().getDeviceFunCodes()) && StringTools.isNotBlank(device.getDevice().getDeviceFunNames())){
    	                        item.setDeviceFunCodes(Arrays.asList(device.getDevice().getDeviceFunCodes().split(",")));
    	                        item.setDeviceFunNames(Arrays.asList(device.getDevice().getDeviceFunNames().split(",")));
    	                    }
    	                    apiResp.getBody().getItems().add(item);
    	                }
        			}
        		}else if(EBusinessType.CDB.index().equals(apiReq.getBody().getBusinessType())) {
        			BatteryCabinetSearch search = new BatteryCabinetSearch();
        			search.setPlaceId(apiReq.getBody().getPlaceId());
        			List<BatteryCabinet> deviceList = BatteryCabinetService.self().findJoinBySearch(search);
        			if(deviceList != null && deviceList.size() > 0) {
        				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
    	                apiResp.getBody().setItems(new ArrayList<>());
    	                for(BatteryCabinet device : deviceList){
    	                    PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
    	                    item.setDeviceSn(device.getDeviceSn());
    	                    item.setDeviceTypeId(device.getDeviceTypeId());
    	                    item.setDeviceTypeName(device.getDeviceTypeName());
    	                    item.setState(device.getState());
    	                    item.setStateName(device.getStateName());
    	                    item.setBindNote(device.getDevice().getBindNote());
    	                    item.setDeployDate(device.getDevice().getDeployDate());
    	                    if(StringTools.isNotBlank(device.getDevice().getDeviceFunCodes()) && StringTools.isNotBlank(device.getDevice().getDeviceFunNames())){
    	                        item.setDeviceFunCodes(Arrays.asList(device.getDevice().getDeviceFunCodes().split(",")));
    	                        item.setDeviceFunNames(Arrays.asList(device.getDevice().getDeviceFunNames().split(",")));
    	                    }
    	                    apiResp.getBody().getItems().add(item);
    	                }
        			}
        		}else if(EBusinessType.CDCZ.index().equals(apiReq.getBody().getBusinessType())) {
        			ChargeSocketSearch search = new ChargeSocketSearch();
        			search.setPlaceId(apiReq.getBody().getPlaceId());
        			List<ChargeSocket> deviceList = ChargeSocketService.self().findJoinBySearch(search);
        			if(deviceList != null && deviceList.size() > 0) {
        				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
    	                apiResp.getBody().setItems(new ArrayList<>());
    	                for(ChargeSocket device : deviceList){
    	                    PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
    	                    item.setDeviceSn(device.getDeviceSn());
    	                    item.setDeviceTypeId(device.getDeviceTypeId());
    	                    item.setDeviceTypeName(device.getDeviceTypeName());
    	                    item.setState(device.getState());
    	                    item.setStateName(device.getStateName());
    	                    item.setBindNote(device.getDevice().getBindNote());
    	                    item.setDeployDate(device.getDevice().getDeployDate());
    	                    if(StringTools.isNotBlank(device.getDevice().getDeviceFunCodes()) && StringTools.isNotBlank(device.getDevice().getDeviceFunNames())){
    	                        item.setDeviceFunCodes(Arrays.asList(device.getDevice().getDeviceFunCodes().split(",")));
    	                        item.setDeviceFunNames(Arrays.asList(device.getDevice().getDeviceFunNames().split(",")));
    	                    }
    	                    apiResp.getBody().getItems().add(item);
    	                }
        			}
        		}else if(EBusinessType.PCL.index().equals(apiReq.getBody().getBusinessType())) {
        			ChargingCableSearch search = new ChargingCableSearch();
        			search.setPlaceId(apiReq.getBody().getPlaceId());
        			List<ChargingCable> deviceList = ChargingCableService.self().findJoinBySearch(search);
        			if(deviceList != null && deviceList.size() > 0) {
        				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
    	                apiResp.getBody().setItems(new ArrayList<>());
    	                for(ChargingCable device : deviceList){
    	                    PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
    	                    item.setDeviceSn(device.getDeviceSn());
    	                    item.setDeviceTypeId(device.getDeviceTypeId());
    	                    item.setDeviceTypeName(device.getDeviceTypeName());
    	                    item.setState(device.getState());
    	                    item.setStateName(device.getStateName());
    	                    item.setBindNote(device.getDevice().getBindNote());
    	                    item.setDeployDate(device.getDevice().getDeployDate());
    	                    if(StringTools.isNotBlank(device.getDevice().getDeviceFunCodes()) && StringTools.isNotBlank(device.getDevice().getDeviceFunNames())){
    	                        item.setDeviceFunCodes(Arrays.asList(device.getDevice().getDeviceFunCodes().split(",")));
    	                        item.setDeviceFunNames(Arrays.asList(device.getDevice().getDeviceFunNames().split(",")));
    	                    }
    	                    apiResp.getBody().getItems().add(item);
    	                }
        			}
        		}else if(EBusinessType.BXSCN_SHOP.index().equals(apiReq.getBody().getBusinessType())) {
        			List<PortableEnergyBattery> batteryList = PortableEnergyBatteryService.self().findByPlaceId(apiReq.getBody().getPlaceId());
	                if (batteryList != null && batteryList.size() > 0) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setItems(new ArrayList<>());
	                    for (PortableEnergyBattery device : batteryList) {
	                        PlaceDeviceListResponse.Item item = new PlaceDeviceListResponse.Item();
	                        item.setDeviceSn(device.getDeviceSn());
	                        item.setDeviceTypeId(device.getType());
	                        item.setDeviceTypeName(device.getTypeName());
	                        item.setState(device.getState());
	                        item.setStateName(device.getStateName());
	                        item.setBindNote(device.getBindNote());
	                        item.setDeployDate(device.getDeployDate());
	                        item.setDeviceFunCodes(new ArrayList<>());
	                        item.getDeviceFunCodes().add(EDeviceFunCode.BXSCN.index());
	                        item.setDeviceFunNames(new ArrayList<>());
	                        item.getDeviceFunNames().add(EDeviceFunCode.BXSCN.note());
	                        apiResp.getBody().getItems().add(item);
	                    }
	                }
        		}
        	}

        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/device/deploy.do")
    public DefaultAPIResponse deployDevice(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "部署失败");
        PlaceDeviceDeployRequest apiReq = WebUtils.getJsonRequest(request, PlaceDeviceDeployRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER,LoginUser.class);
            if(loginUser != null ) {
                //去除设备序列号中的空格
                String deviceSn = apiReq.getBody().getDeviceSn().replace(" ","").replace("-","");
                Device device = null;
                PortableEnergyBattery portableEnergyBattery = null;
                //检查权限
                if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                	device = DeviceService.self().getByDeviceSn(deviceSn);
                    if(device != null) {
                    	if (device.getPlaceId() != null) {
                             apiResp.setMsg("设备已部署");
                             return apiResp;
                        }
                    	
                    	if(device.getUserId() != null && !device.getUserId().equals(loginUser.getId())) {
                    		apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"该设备不属于你，无权限操作");
                            return apiResp;
                    	}
                    }else if(BaseConstants.getBXSCN()) {
                    	 portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
	                     if (portableEnergyBattery != null) {
	                    	 if(portableEnergyBattery.getUserId() != null && portableEnergyBattery.getUserId().equals(loginUser.getId())) {
	                    		 if (portableEnergyBattery.getPlaceId() != null) {
	                                 apiResp.setMsg("电池已部署");
	                                 return apiResp;
	                             }
	                    	 }else {
	                    		 apiResp.setMsg("电池无权限部署");
	                    		 return apiResp;
	                    	 }
	                     }else {
	                    	 log.error("设备部署，未能找到设备信息，设备序列号：{{0}}", deviceSn);
	                    	 apiResp.setMsg("未找到设备信息");
	                         return apiResp;
	                     }
                    }else {
                    	log.error("设备部署，未能找到设备信息，设备序列号：{{0}}", deviceSn);
                    	apiResp.setMsg("未找到设备信息");
                        return apiResp;
                    }
                }else if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())) {
                	AgentRelationDevice relationDevice = AgentRelationDeviceService.self().getJoinByKeys(loginUser.getParentId(),loginUser.getId(),deviceSn);
                    if(relationDevice != null){
                    	device = relationDevice.getDevice();
                        if (device.getPlaceId() != null) {
                            apiResp.setMsg("设备已部署");
                            return apiResp;
                        }
                    }else{
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"该设备不属于你，无权限操作");
                        return apiResp;
                    }
                }else {
                	apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                }
                
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getJoinById(apiReq.getBody().getPlaceId());
                if (physicalStore == null) {
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }
                
                if(device != null){
            		device.setPlaceId(apiReq.getBody().getPlaceId());
                    device.setPlaceName(physicalStore.getName());
                    device.setUserId(physicalStore.getUserId());
                    device.setUserName(physicalStore.getUser().getName());
                    device.setUserPhone(physicalStore.getUser().getPhone());
                    device.setProvince(physicalStore.getProvince());
                    device.setCity(physicalStore.getCity());
                    device.setCityArea(physicalStore.getCityArea());
                    device.setAreaCode(physicalStore.getAreaCode());
                    device.setBindNote(apiReq.getBody().getBindNote());

                    try {
                        if (DeviceService.self().deploy(device, PlacePhysicalStoreService.self())) {
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else if(BaseConstants.getBXSCN()) {
                	try {
	                     if (portableEnergyBattery != null) {
	                         if (PortableEnergyBatteryService.self().deploy(portableEnergyBattery,physicalStore
	                        		 ,apiReq.getBody().getBindNote(),PlacePhysicalStoreService.self())) {
	                             apiResp.setCode(DtoConstants.SUCCESS, null);
	                         }
	                     } 
                	} catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }else {
            	apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/device/undeploy.do")
    public DefaultAPIResponse undeployDevice(HttpServletRequest request){
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"移除部署失败");
        PlaceDeviceUndeployRequest apiReq = WebUtils.getJsonRequest(request,PlaceDeviceUndeployRequest.class);
        if(apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER,LoginUser.class);
            if(loginUser != null) {
                //去除设备序列号中的空格
                String deviceSn = apiReq.getBody().getDeviceSn().replace(" ","").replace("-","");
                Device device = null;
                PortableEnergyBattery portableEnergyBattery  = null;
                //检查权限
                if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                	device = DeviceService.self().getByDeviceSn(deviceSn);
                    if(device != null) {
                    	if (device.getPlaceId() == null) {
                             apiResp.setMsg("设备未部署");
                             return apiResp;
                        }
                    	
                    	if(device.getUserId() == null || !device.getUserId().equals(loginUser.getId())) {
                    		apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"该设备不属于你，无权限操作");
                            return apiResp;
                    	}
                    }else if(BaseConstants.getBXSCN()) {
                    	portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
	                     if (portableEnergyBattery != null) {
	                    	 if(portableEnergyBattery.getUserId() != null && portableEnergyBattery.getUserId().equals(loginUser.getId())) {
	                    		 if (portableEnergyBattery.getPlaceId() == null) {
	                                 apiResp.setMsg("电池未部署");
	                                 return apiResp;
	                             }
	                    	 }else {
	                    		 apiResp.setMsg("电池无权限部署");
	                    		 return apiResp;
	                    	 }
	                     }else {
	                    	 log.error("设备移除部署，未能找到设备信息，设备序列号：{{0}}", deviceSn);
	                    	 apiResp.setMsg("未找到设备信息");
	                         return apiResp;
	                     }
                    }else {
                    	 log.error("设备移除部署，未能找到设备信息，设备序列号：{{0}}", deviceSn);
                    	 apiResp.setMsg("未找到设备信息");
                         return apiResp;
                    }
                }else if(ELoginUserRoleType.Partner.index().equals(loginUser.getRoleType())){
                    AgentRelationDevice relationDevice = AgentRelationDeviceService.self().getJoinByKeys(loginUser.getParentId(),loginUser.getId(),deviceSn);
                    if(relationDevice != null){
                        device = relationDevice.getDevice();
                    }else{
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"该设备不属于你，无权限操作");
                        return apiResp;
                    }
                }else {
                	apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"该设备不属于你，无权限操作");
                    return apiResp;
                }

                if (device != null) {
                    try {
                        if (DeviceService.self().undeploy(device, PlacePhysicalStoreService.self())) {
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else if(BaseConstants.getBXSCN()) {
                	try {
	                    if (portableEnergyBattery != null) {
	                    	if (PortableEnergyBatteryService.self().undeploy(portableEnergyBattery)) {
	                    		apiResp.setCode(DtoConstants.SUCCESS, null);
		                    }
	                    } 
	                } catch (LogicException e) {
	                    apiResp.setMsg(e.getMessage());
	                }
                }
            }else{
                apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            }
        }
        return apiResp;
    }

}
